import { message } from 'antd';
import { queryFavoritePage, queryPageDetail, removeFav } from '@/services/favoritePage';

export default {
  namespace: 'favoritePage',

  state: {
    pageList: {}, // 格式为{data_list: [{…}], total_count: 1}
    pageDetail: {},
  },

  effects: {
    *queryPageList({ payload }, { call, put }) {
      try {
        // 清空数据
        yield put({
          type: 'setPayload',
          payload: {
            pageList: {},
          },
        });
        const res = yield call(queryFavoritePage, payload.page_size, payload.page_num);
        if (+res.code === 0) {
          yield put({
            type: 'setPayload',
            payload: {
              pageList: res.data,
            },
          });
        } else {
          message.error(res.message);
        }
      } catch (e) {
        console.log(e);
        // message.error('服务暂时不可用，请稍后再试！');
      }
    },
    *queryDetail({ payload }, { call, put }) {
      try {
        const res = yield call(queryPageDetail, payload.id, payload.type);
        if (+res.code === 0) {
          yield put({
            type: 'setPayload',
            payload: {
              pageDetail: res.data,
            },
          });
        } else {
          return Promise.reject(new Error(res.message));
        }
      } catch (e) {
        return Promise.reject(new Error(e.message));
      }
    },
    *remove({ payload }, { call, put }) {
      try {
        const res = yield call(removeFav, payload);
        if (+res.code === 0) {
          message.success('删除成功！');
        } else {
          message.error(res.message);
        }
      } catch (e) {
        console.log(e);
        message.error('删除失败，请稍后再试');
      }
    },
  },

  reducers: {
    setPayload(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
